import React, { Component } from 'react';
import './scss/NoticeDetails.scss';
import { Spin, message } from 'antd';
import { getData, getQueryVariable, putData1 } from '../../common/js/fetch';
import Alert from '../../common/compont/alert_dialog_wrapper';
import {
    LgButton, LgSelect, LgBlockCard, LgBlockCardBox, LgDatePicker, LgSearch, LgPaginationA,
    LgBlockCardBoxProps, LgPopLayer, LgDrawer, LgInput, LgCheckbox, LgTextarea, LgSwitch
} from 'lancoo-web-ui';
import { createHashHistory } from 'history';
import { Scrollbars } from 'react-custom-scrollbars';
import LgTopBar from './common/header/Header'
import Base64 from '../../common/js/fetch/base64'
import { saveAs } from 'file-saver'
import moment from 'moment';

function GetExtensionFileName(pathfilename) {
    var reg = /(\\+)/g;
    var pfn = pathfilename.replace(reg, "#");
    var arrpfn = pfn.split("#");
    var fn = arrpfn[arrpfn.length - 1];
    var arrfn = fn.split(".");
    return arrfn[arrfn.length - 1];
}
const schoolInfo = JSON.parse(sessionStorage.getItem('schoolSystemInfo')) || '';
class Noticedetails extends Component {

    constructor(props) {
        super(props);
        console.log(props, 'detail');
        this.state = {
            message: {},
            data: [],
            editState: 0, //编辑状态，0表示查看，1表示编辑
            loading: true,
            changeTabFlag: false,
            attachmentList: [],
        };

    }

    showhtml(htmlString) {
        var html = { __html: htmlString };
        return <div dangerouslySetInnerHTML={html}></div>;
    }
    componentDidMount() {
        let token = getQueryVariable('lg_tk');
        let bulletinId = getQueryVariable('bulletinId');
        let isFromMsg = getQueryVariable('isFromMsg');
        if (!token) {
            token = sessionStorage.getItem('token');
        }
        let url = 'api/bulletin/info/board/detail'
        if (getQueryVariable('isManage') == '1') {
            url = 'api/bulletin/info/release/detail'
        }
        // 将 getData 的返回值转换成 promise 对象
        let handleGetData = async () => {
            return new Promise(resolve => {
                getData(url, { bulletinId }).then(res => {
                    resolve(res.json());
                });
            });
        };

        // 异步等待 setRead 方法执行完成
        let handleSetRead = async () => {
            if (isFromMsg == 1) {
                await this.setRead(bulletinId);
            }
        };

        handleSetRead().then(() => {
            setTimeout(() => {
                handleGetData().then(json => {
                    console.log(json, 'json1112');
                    if (json.code == 200 && json.data) {
                        let data = json.data;
                        this.setState({
                            data: data,
                            state: 0,
                            attachmentList: data?.attachmentList ? data?.attachmentList : [],
                        }, () => {
                            this.setState({
                                loading: false
                            })
                            if (window.opener) {
                                window.opener.postMessage('11', '*');
                            }
                        })
                    } else {
                        this.setState({
                            changeTabFlag: true
                        })
                    }
                });
            }, 250);
        });
    }

    //增加阅读量并设置已读
    setRead = (bulletinId) => {
        let userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
        putData1('api/bulletin/manage/read/increment', {
            bulletinId,
            userId: userInfo.userId
        }).then((res) => {
            return res.json()
        }).then((res) => {
            if (res.code == 200) {
                // message.success('已读~');
            } else {
                message.error(res.msg, 3);
            }
        })
    }

    toErrorPage() {
        const history = createHashHistory();
        history.push('/Error');
        return
    };


    downFile(url, name) {
        let data = this.state.data
        message.config({
            top: 50,
        })
        const hide = message.loading('正在下载，请稍等..', 0);
        var x = new XMLHttpRequest();
        // let url1 = sessionStorage.getItem('itemUrl') + url;
        console.log(url, 'url1');
        x.open("GET", url, true);
        x.responseType = 'blob';
        x.onload = function (e) {
            hide()
            var url = window.URL.createObjectURL(x.response);
            var a = document.createElement('a');
            a.href = url;
            a.download = name;
            a.click();
            URL.revokeObjectURL(url);
        }
        x.send();
    };

    //全部下载
    downloadFiles(files) {
        files.forEach(file => {
            fetch(file.url)
                .then(res => res.blob())
                .then(blob => {
                    saveAs(blob, file.name);
                });
        });
    }

    // 预览附件
    preViewFile(item) {
        let filePath = '';
        if (item.url.indexOf('http://') > -1 || item.url.indexOf('https://') > -1) {
            filePath = item.url;
        } else {
            filePath = schoolInfo.itemUrl + '/' + item.url;
        }
        filePath = filePath.replace(/[\\]+/g, '/');
        let base64 = new Base64();
        let url = encodeURIComponent(base64.encode(filePath));
        let previewIP = JSON.parse(sessionStorage.getItem("previewIP"));
        let webSvrAddr = previewIP.webSvrAddr;
        let schoolId = schoolInfo.schoolId
        window.open(`${webSvrAddr}onlinePreview?url=${url}&schoolId=${schoolId}`);
    }
    changeTab(data) {
        if (data) {
            window.opener = null;
            window.open('', '_self');
            window.close();
        }
    }
    render() {
        let {
            attachmentList,
            data
        } = this.state
        return (
            <div >
                <Alert
                    noCancel={true}
                    isConfirm={true}
                    className="sendAgain-alert"
                    message="您未拥有查看该公告的权限或该公告已被撤回"
                    isOpen={this.state.changeTabFlag}
                    chooseFn={(data) => { this.changeTab(data) }}>
                </Alert>
                <div>
                    <LgTopBar ></LgTopBar>
                    <LgBlockCardBox className="g002-bg lg-skin-s2 notice-detail">
                        <LgBlockCard className=' g002-blockCard-1 notice-details-middle'>
                            <h1>{data.title}</h1>
                            {this.state.editState === 1 ? <p className='notice-details-message'><span><b> 发布者: </b>{data.userName} </span><span style={{ color: '#999999' }}> <b>发布时间: </b>{data.releaseTime}</span><span><b> 阅读次数:  </b>{data.readCount ? data.readCount : '0'}次</span></p>
                                : <div className='notice-details-message'><span > <i className='publish-icon publish-icon-time'> </i>{moment(data.releaseTime).format('YYYY-MM-DD')}</span>
                                    <span > <i className='publish-icon publish-icon-dep'></i>{data.departmentName}</span><span><i className='publish-icon publish-icon-type'> </i>{data.typeName} </span>
                                    <span><i className='publish-icon publish-icon-read'></i>{data.readCount ? data.readCount : '0'}</span></div>}
                            <div className="notice-content ">{this.showhtml(data.content)}</div>
                            <i className='hor-line'></i>
                            {attachmentList.length > 0 ? <div className="notice-down-box" >
                                <p style={{ marginBottom: '15px', display: 'flex' }}>附件({attachmentList.length}个)
                                    <div className='download-all'
                                        onClick={() => this.downloadFiles(attachmentList)}>全部下载</div>
                                </p>
                                {/* <Scrollbars autoHeight autoHeightMax={180} autoHide autoHideTimeout={100}> */}
                                {
                                    attachmentList.map(item => {
                                        return (
                                            <div className="notice-down-message">
                                                <div className='file-info'>
                                                    <i className={`file-icon file-icon-${GetExtensionFileName(item.name)}`}></i>
                                                    <p className='file-name' title={item.name.length > 60 ? item.name : ''}>{item.name.length > 60 ? item.name.slice(0, 58) + '..' : item.name}</p>
                                                    <span className='file-size'>{(item / 1024 / 1024) >= 1 ? (item.size / 1024 / 1024).toFixed(1) + 'MB' : (item.size / 1024).toFixed(1) + 'KB'}</span>
                                                </div>
                                                <div>
                                                    <LgButton onClick={() => this.preViewFile(item)} split shapeType='text' type='info'>预览</LgButton>
                                                    <LgButton onClick={() => { this.downFile(item.url, item.name); }} split shapeType='text' type='info'>下载</LgButton>
                                                </div>
                                                {/* <b className='down-file' href={item.url.indexOf('.mp4') === -1 && item.url.indexOf('.mp4') === -1 ? item.url : item.url + '?filename=' + item.name.slice(0, -4)} download={item.name} onClick={() => { this.downFile(item.url, item.name); }}>下载</b> */}
                                            </div>
                                        )
                                    })
                                }
                                {/* </Scrollbars> */}

                            </div> : ''}
                        </LgBlockCard>
                    </LgBlockCardBox>
                </div>
            </div>
        )

    }

}

export default Noticedetails;